﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;
using System.Web.UI.WebControls;
using Lucene.Net.Store;
using System.IO;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Documents;
using PanGu;
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.PanGu;

/// <summary>
///common 的摘要说明
/// </summary>
public class common
{
	public common()
	{
		//
		//TODO: 在此处添加构造函数逻辑
		//
	}

    #region 删除图片
    /// <summary>
    /// 删除图片
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    public static bool deleteFile(string path)
    {
        bool ret = false;
        string p = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;

        System.IO.FileInfo file = new System.IO.FileInfo(@"~\imgpublish\"+path);
        if (file.Exists)
        {
            file.Delete();
            ret = true;
        }
        return ret;

    } 
    #endregion

    #region 获得前三的热词(缓存)
    /// <summary>
    /// 获得前三的热词
    /// </summary>
    /// <param name="keyword"></param>
    /// <returns></returns>
    public static List<MODEL.Search> getKeyWord()
    {
        var data = HttpRuntime.Cache["hotwords"];
        if (data == null)
        {
            List<MODEL.Search> hotwords = new DAL.Search().getKeyWord();
            if (hotwords != null)
            {
                HttpRuntime.Cache.Insert("hotwords", hotwords, null, DateTime.Now.AddSeconds(60), TimeSpan.Zero);
            }
            return hotwords;
        }
        else
        {
            return (List<MODEL.Search>)data;
        }
    }
    #endregion
    
    #region 搜索 返回一个lostandfound实体对象集合
    /// <summary>
    /// 搜索 返回一个lostandfound实体对象集合
    /// </summary>
    /// <param name="keyword"></param>
    /// <returns></returns>
    public static List<MODEL.LostAndFound> searchByKW(string keyword,int startIndex,int pageSize,out int totalCount)
    {
        //string indexPath = "c:/index";

        string path = HttpContext.Current.Request.PhysicalApplicationPath + "index";
        string kw = keyword;
        //保存索引文件到名字为indexPath文件夹中（FSDirectory：保存索引文件到文件中）
        //FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());

        //IndexReader对索引文件进行读取的类
        //IndexReader reader = IndexReader.Open(directory, true);

        IndexReader reader = IndexReader.Open(path);
        //IndexSearcher进行搜索的类，构造函数中传递IndexReader类实体
        IndexSearcher searcher = new IndexSearcher(reader);
        //PhraseQuery对多个关键词进行搜索
        PhraseQuery query = new PhraseQuery();

        //todo:把用户输入的关键词进行拆词

        foreach (string word in SplitWord(keyword))//先用空格，让用户去分词，空格分隔的就是词“计算机 专业”
        {
            //body中含有word关键词
            query.Add(new Term("body", word));
        }
        //query.Add(new Term("body","计算机"));
        //query.Add(new Term("body", "专业"));
        //设置关键词之间的最大距离
        query.SetSlop(100);
        //结果收集器，设置为最大收集为1000
        TopScoreDocCollector collector = TopScoreDocCollector.create(1000, true);
        //通过search方法根据query条件进行搜索
        searcher.Search(query, null, collector);
        totalCount = collector.GetTotalHits();//返回总条数
        ScoreDoc[] docs = collector.TopDocs(startIndex, pageSize).scoreDocs;
        List<MODEL.LostAndFound> listResult = new List<MODEL.LostAndFound>();
        for (int i = 0; i < docs.Length; i++)
        {
            int docId = docs[i].doc;//取到文档的编号（主键，这个是Lucene .net分配的）
            //检索结果中只有文档的id，如果要取Document，则需要Doc再去取
            //降低内容占用
            Document doc = searcher.Doc(docId);//根据id找Document
            string number = doc.Get("number");
            string title = doc.Get("title");
            string body = doc.Get("body");

            MODEL.LostAndFound result = new MODEL.LostAndFound();
            result.LId = Convert.ToInt32(number);
            result.GoodsName = title;


            result.Feature = Preview(body, keyword);

            listResult.Add(result);
        }
        return listResult;
    } 
    #endregion 

    #region 字体高亮
    /// <summary>
    /// 字体高亮
    /// </summary>
    /// <param name="body"></param>
    /// <param name="keyword"></param>
    /// <returns></returns>
    private static string Preview(string body, string keyword)
    {
        //创建HTMLFormatter,参数为高亮单词的前后缀 
        PanGu.HighLight.SimpleHTMLFormatter simpleHTMLFormatter =
               new PanGu.HighLight.SimpleHTMLFormatter("<font color=\"red\">", "</font>");
        //创建 Highlighter ，输入HTMLFormatter 和 盘古分词对象Semgent 
        PanGu.HighLight.Highlighter highlighter =
                        new PanGu.HighLight.Highlighter(simpleHTMLFormatter,
                        new Segment());
        //设置每个摘要段的字符数 
        highlighter.FragmentSize = 60;
        //获取最匹配的摘要段 
        String bodyPreview = highlighter.GetBestFragment(keyword, body);
        return bodyPreview;
    } 
    #endregion

    #region 盘古分词 返回一个字符串数组
    /// <summary>
    /// 盘古分词 返回一个字符串数组
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string[] SplitWord(string str)
    {
        List<string> list = new List<string>();
        Analyzer analyzer = new PanGuAnalyzer();
        TokenStream tokenStream = analyzer.TokenStream("", new StringReader(str));
        Lucene.Net.Analysis.Token token = null;
        while ((token = tokenStream.Next()) != null)
        {
            list.Add(token.TermText());
        }
        return list.ToArray();
    } 
    #endregion

    #region 退出
    /// <summary>
    /// 退出
    /// </summary>
    public static void LoginOut()
    {
        HttpContext context = HttpContext.Current;
        context.Session["currentUser"] = null;
        if (context.Request.Cookies["name"] != null && context.Request.Cookies["pwd"] != null)
        {
            context.Response.Cookies["name"].Expires = DateTime.Now.AddDays(-1);
            context.Response.Cookies["pwd"].Expires = DateTime.Now.AddDays(-1);
        }
        context.Response.Redirect(HttpContext.Current.Request.Url.ToString());
        
    } 
    #endregion

    #region 根据session与cookies判断是否登录或记住我
    /// <summary>
    /// 根据session与cookies判断是否登录或记住我
    /// </summary>
    /// <returns></returns>
    public static bool isLoginOrNot()
    {
        if (HttpContext.Current.Session["currentUser"] != null || common.isLoginByCookie())
        {
            MODEL.Users user = (MODEL.Users)HttpContext.Current.Session["currentUser"];
            BLL.Users bllusers=new BLL.Users();
            if (bllusers.Exist(user.UName, user.Pwd))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    } 
    #endregion

    #region 根据cookies判断（记住我）
    /// <summary>
    /// 根据cookies判断（记住我）
    /// </summary>
    /// <returns></returns>
    public static bool isLoginByCookie()
    {
        if (HttpContext.Current.Request.Cookies["name"] != null && HttpContext.Current.Request.Cookies["pwd"] != null)
        {
            string name = HttpContext.Current.Request.Cookies["name"].Value;
            string pwd = HttpContext.Current.Request.Cookies["pwd"].Value;
            MODEL.Users model = new BLL.Users().getModel(name);
            if (model != null)
            {
                string sypwd = Encrypt(model.Pwd, pwd.Substring(0, 2));
                if (sypwd == pwd)
                {
                    //最终还是以session存放model
                    HttpContext.Current.Session["currentUser"] = model;
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    } 
    #endregion

    #region MD5加密
    /// <summary>
    /// MD5加密
    /// </summary>
    /// <param name="sDataIn"></param>
    /// <returns></returns>
    public static string GetMD5(string sDataIn)
    {
        MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
        byte[] bytValue, bytHash;
        bytValue = System.Text.Encoding.UTF8.GetBytes(sDataIn);
        bytHash = md5.ComputeHash(bytValue);
        md5.Clear();
        string sTemp = "";
        for (int i = 0; i < bytHash.Length; i++)
        {
            sTemp += bytHash[i].ToString("X").PadLeft(2, '0');
        }
        return sTemp.ToLower();
    } 
    #endregion

    #region 对输入的密码进行加密，以便存到cookie中(记住我)
    /// <summary>
    /// 对输入的密码进行加密，以便存到cookie中(记住我)
    /// </summary>
    /// <param name="txt"></param>
    /// <returns></returns>
    public static string Encrypt(string txt, string key)
    {
        string strEncrypt;
        string rd;
        if (key.Length == 0)
        {
            //产生一个两位的字符串（所谓的盐）
            rd = ((char)new Random().Next(68, 91)).ToString() + ((char)new Random().Next(68, 91)).ToString();
        }
        else
        {
            rd = key;
        }
        strEncrypt = rd + GetMD5(rd + GetMD5(txt));
        return strEncrypt;
    } 
    #endregion
}